package project.Controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import project.Pojo.Chat.AI.ChatRecord;
import project.Pojo.Chat.ChatRoom;
import project.Pojo.Chat.ChatRoomUser;
import project.Pojo.RequestJsonPojo.Message;
import project.Pojo.Result;
import project.Service.ChatService;

import java.util.List;

@Controller
@RestController
@CrossOrigin
@RequestMapping("/chat")
@Tag(name = "聊天室相关接口")
public class ChatController {
    @Autowired
    ChatService chatService;


    @GetMapping("/getrecord")
    List<ChatRecord> getAiRecordByUserId(@RequestParam("userid") String userId) {
        return chatService.getRecordByUserId(userId);
    }

    @PostMapping("/new")
    String newChatRoom(String name, String admin) {
        chatService.insertRoom(name, admin);
//        查询当前新增聊天室的自增id，用于添加聊天室用户
        int id = chatService.selectRoomId(name);
//        添加聊天室用户
        chatService.insertRoomUser(admin, id);
        return "ws://localhost:8080/chat/" + id;
    }

    @PostMapping("/delete/room")
    Result deleteRoom(int id) {
        List<ChatRoom> list = chatService.selectRoomById(id);
        if (list.isEmpty()) return Result.error("该聊天室不存在");
        chatService.deleteRoom(id);
        return Result.success();
    }

    @PostMapping("/new/user")
    Result newRoomUser(String username, int id) {
        ChatRoomUser c = chatService.selectRoomUserByRoomIdAndUsername(id, username);
        if (c == null) return Result.error("该聊天室不存在该用户");
        chatService.insertRoomUser(username, id);
        return Result.success();
    }


    @PostMapping("/delete/user")
    Result deleteUser(int roomId, String username) {
        ChatRoomUser chatRoomUser = chatService.selectRoomUserByRoomIdAndUsername(roomId, username);
        if (chatRoomUser == null) return Result.error("当前聊天室不存在此用户");
        chatService.selectRoomUserByRoomIdAndUsername(roomId, username);
        return Result.success();
    }

    @PostMapping("/ai/call")
    Result<String> callAi(@RequestBody Message message) {
        return chatService.callAi(message);
    }

//    //群聊和私聊接口：
//
//    //用来推送消息
//    private final SimpMessagingTemplate messagingTemplate;
//
//    //实例化时注入
//    public ChatController(SimpMessagingTemplate messagingTemplate) {
//        this.messagingTemplate = messagingTemplate;
//    }


}
